const { Controller } = require('egg');

class CategoriesController extends Controller {
  // 查询分类
  async index() {
    const { ctx } = this;
    const result = await ctx.service.categories.findAll(ctx.query);
    ctx.success(result, '查询分类信息成功');
  }

  // 添加
  async create() {
    const { ctx } = this;
    const categories = ctx.request.body;
    const result = await ctx.service.categories.add(categories);
    ctx.success(result, '添加分类信息成功');
  }

  // 删除
  async destroy() {
    const { ctx } = this;
    const { id } = ctx.params;
    const success = await ctx.service.categories.remove(id);
    if (success) {
      ctx.success(null, '类别删除成功');
    } else {
      ctx.error('类别删除失败');
    }
  }

  // 修改
  async update() {
    const { ctx } = this;
    const id = ctx.params.id;
    const success = await ctx.service.categories.modify(ctx.request.body, id);
    if (success) {
      ctx.success(null, '类别更新成功');
    } else {
      ctx.error('类别更新失败');
    }
  }

  // 查询单条数据
  async show() {
    const { ctx } = this;
    const id = ctx.params.id;
    const result = await ctx.service.categories.findById(id);
    ctx.success(result, `查询id为${id}的类别信息成功`);
  }
}

module.exports = CategoriesController;
